import React, { PureComponent, Fragment } from "react";
import ReactDOM from "react-dom";
import { Table, Alert } from "antd";
import { connect } from "dva";
import styles from "./index.less";

function initTotalList(columns) {
  const totalList = [];
  columns.forEach((column) => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

@connect(({ global }) => ({
  windowSize: global.windowSize,
}))
class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns, showAlert } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
      showAlert,
      offsetTop: 0,
    };
  }
  componentDidMount() {
    const dom = ReactDOM.findDOMNode(this);
    let offsetTop = this.getNodeOffsetTop(dom);
    this.setState({ offsetTop: offsetTop + 54 + 72 + 24 + 24 });
  }
  getNodeOffsetTop = (node) => {
    let top = node.offsetTop,
      parent = node.offsetParent;
    while (parent !== null) {
      top += parent.offsetTop;
      parent = parent.offsetParent;
    }
    return top;
  };
  static getDerivedStateFromProps(nextProps) {
    // clean state
    const { showCheckbox, selectedRows } = nextProps;
    if (showCheckbox && selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map((item) => ({
      ...item,
      total: selectedRows.reduce(
        (sum, val) => sum + parseFloat(val[item.dataIndex], 10),
        0
      ),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList, showAlert, offsetTop } = this.state;
    const {
      data = { list: [], pagination: {} },
      rowKey,
      showCheckbox,
      columns,
      scroll,
      windowSize,
      autoCalc = true,
      customSelection,
      ...rest
    } = this.props;
    const { list, pagination } = data;

    // 因为tableLayout='fixed'的原因,序号列会加宽,所以将序号列固定宽度
    const fmtColumns = columns.map((item) => {
      if (item.title === "序号") {
        return Object.assign(item, { width: 100 });
      }
      return item;
    });

    let paginationProps = false;
    if (`${this.props.pagination}` !== "false") {
      paginationProps = {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["10", "20", "30", "50"],
        ...pagination,
        // current: pagination.currentPage,
        // total: pagination.totalResult,
        // showTotal: (total) => `共 ${total} 条`,
      };
    }
    let rowSelection = null;
    if (showCheckbox) {
      rowSelection = {
        selectedRowKeys,
        onChange: this.handleRowSelectChange,
        getCheckboxProps: (record) => ({
          disabled: record.disabled,
        }),
        ...customSelection,
      };
    }
    let columnLength = showCheckbox ? columns.length - 2 : columns.length - 1;
    const scrollWidth = columnLength < 0 ? 0 : columnLength * 200;
    let scrollSet = { x: 0, y: 0 };
    if (autoCalc) {
      scrollSet =
        list.length !== 0
          ? { x: scrollWidth, y: windowSize.height - offsetTop }
          : { x: 0, y: 0 };
      if (scroll && scroll.y) {
        scrollSet = { ...scrollSet, y: scroll.y };
      }
    }
    return (
      <div className={styles.standardTable}>
        {showAlert && (
          <div className={styles.tableAlert}>
            <Alert
              message={
                <Fragment>
                  已选择{" "}
                  <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a>{" "}
                  项&nbsp;&nbsp;
                  {needTotalList.map((item) => (
                    <span style={{ marginLeft: 8 }} key={item.dataIndex}>
                      {item.title}
                      总计&nbsp;
                      <span style={{ fontWeight: 600 }}>
                        {item.render ? item.render(item.total) : item.total}
                      </span>
                    </span>
                  ))}
                  <a
                    onClick={this.cleanSelectedKeys}
                    style={{ marginLeft: 24 }}
                  >
                    清空
                  </a>
                </Fragment>
              }
              type="info"
              showIcon
            />
          </div>
        )}
        <Table
          tableLayout="fixed"
          rowKey={rowKey || "key"}
          rowSelection={rowSelection}
          dataSource={list}
          onChange={this.handleTableChange}
          columns={fmtColumns}
          {...rest}
          pagination={paginationProps}
          scroll={scrollSet}
        />
      </div>
    );
  }
}

export default StandardTable;
